package com.uniview.task;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.uniview.entity.po.MailConfig;
import com.uniview.entity.po.MailLog;
import com.uniview.entity.po.MailSendpeople;
import com.uniview.entity.vo.MailMsg;
import com.uniview.entity.vo.OrderDetailReport;
import com.uniview.service.MailConfigService;
import com.uniview.service.MailLogService;
import com.uniview.service.MailSendpeopleService;
import com.uniview.service.report.OrderDetailReportService;
import com.uniview.util.mail.SimpleMailSenderDB;
/**
 * 定时任务--不满意工单邮催
 * @author 
 *
 */
public class DissatisfiedMailTask {

	private Logger logger = Logger.getLogger(DissatisfiedMailTask.class);

	@Autowired
	private MailConfigService mailConfigService;

	@Autowired
	private MailSendpeopleService mailSendpeopleService;

	@Autowired
	private OrderDetailReportService orderDetailReportService;

	@Autowired
	private MailLogService mailLogService;

	public synchronized void dissatisfiedMail() {
		try {
			logger.debug("=========开始执行不满意工单邮催任务");
			// 查询当天的邮催发送日志
			List<MailLog> mailLogList = mailLogService.findmailLogBySysdate();
			if (mailLogList.size() > 0) {
			} else {
				// 获取不满意未处理工单内容
				List<OrderDetailReport> orderDetailReportList = orderDetailReportService
						.findDissatisfiedOrderReoprt();
				MailLog mailLogDB = new MailLog();
				if (orderDetailReportList.size() > 0) {
					// 获取邮箱服务器配置
					List<MailConfig> mailConfigList = mailConfigService
							.findAllMailConfig();
					if (mailConfigList.size() > 0) {
						// 设置邮箱服务器
						MailConfig mailConfig = mailConfigList.get(0);
						SimpleMailSenderDB simpleMailSender = new SimpleMailSenderDB(
								mailConfig.getHost(), String.valueOf(mailConfig
										.getPort()), "true",
								mailConfig.getSendMail(),
								mailConfig.getPassword());
						simpleMailSender.init();
						// 获取邮件收件人列表
						List<MailSendpeople> mailSendpeopleBySend = mailSendpeopleService
								.findSendByMail();
						if (mailSendpeopleBySend.size() > 0) {
							// 邮件收件人处理
							List<String> recipientBySendList = new ArrayList<String>();
							StringBuilder recipientsBySend = new StringBuilder();
							for (int i = 0; i < mailSendpeopleBySend.size(); i++) {
								recipientBySendList.add(mailSendpeopleBySend
										.get(i).getSendMail());
								recipientsBySend.append(mailSendpeopleBySend
										.get(i).getSendMail());
								recipientsBySend.append(";");
							}
							String recipientsBySendStr = recipientsBySend
									.toString().substring(0,
											recipientsBySend.length() - 1);
							// 获取邮件抄送人列表
							List<MailSendpeople> mailSendpeopleByCC = mailSendpeopleService
									.findCCByMail();
							// 邮件抄送人处理
							List<String> recipientByCCList = new ArrayList<String>();
							StringBuilder recipientsByCC = new StringBuilder();
							for (int i = 0; i < mailSendpeopleByCC.size(); i++) {
								recipientByCCList.add(mailSendpeopleByCC.get(i)
										.getSendMail());
								recipientsByCC.append(mailSendpeopleByCC.get(i)
										.getSendMail());
								recipientsByCC.append(";");
							}
							String recipientsByCCStr = recipientsByCC
									.toString().substring(0,
											recipientsByCC.length() - 1);
							// 设置邮件的主题
							String subject = "派工系统邮催提醒：您有不满意工单需要处理，请及时跟进！";

							// 设置邮件的内容
							StringBuilder content = new StringBuilder(
									"<html><head></head><body>");
							content.append("<table border=\"5\" style=\"border:solid 1px #000000;font-size:24px;border-collapse:collapse;\">");
							content.append("<tr style=\"color:#000000\"><th>NO</th><th>工单编号</th><th>工单类型</th>"
									+ "<th>工单提出人</th><th>工单处理人</th><th>所在办事处</th><th>客户名称</th><th>工单生成时间</th><th>工单处理时间</th><th>工单结束时间</th>"
									+ "<th>工单总工时</th><th>客户满意度</th></tr>");
							for (int i = 0; i < orderDetailReportList.size(); i++) {
								OrderDetailReport orderDetailReport = orderDetailReportList
										.get(i);
								int index = i + 1;
								content.append("<tr>");
								content.append("<td>" + index + "</td>");
								content.append("<td>"
										+ orderDetailReport.getOrderNo()
										+ "</td>");
								content.append("<td>"
										+ orderDetailReport.getOrderFrom()
										+ "</td>");
								content.append("<td>"
										+ orderDetailReport.getCreator()
										+ "</td>");
								content.append("<td>"
										+ orderDetailReport.getHandle()
										+ "</td>");
								content.append("<td>"
										+ orderDetailReport.getArea() + "</td>");
								content.append("<td>"
										+ orderDetailReport.getCustomerName()
										+ "</td>");
								content.append("<td>"
										+ getTimestampToString(orderDetailReport.getCreateTime())
										+ "</td>");
								content.append("<td>"
										+ getTimestampToString(orderDetailReport.getStartTime())
										+ "</td>");
								content.append("<td>"
										+ getTimestampToString(orderDetailReport.getEndTime())
										+ "</td>");
								BigDecimal orderHour = fixed(orderDetailReport
										.getOrderHours());
								content.append("<td>" + orderHour + "</td>");
								String satisfaction = "";
								if (orderDetailReport.getSatisfaction() == 0) {
									satisfaction = "不满意";
								} else {
									satisfaction = "满意";
								}
								content.append("<td>" + satisfaction + "</td>");
								content.append("</tr>");
							}
							content.append("</table>");
							content.append("</body></html>");
							MailMsg mailMsg = simpleMailSender.send(
									recipientBySendList, recipientByCCList,
									subject, content);
							mailLogDB.setFlag(mailMsg.getSendFlag());
							mailLogDB.setRemarks(mailMsg.getSendMag());
							mailLogDB.setCcStr(recipientsByCCStr);
							mailLogDB.setSendStr(recipientsBySendStr);
						} else {
							mailLogDB.setFlag(3);
							mailLogDB.setRemarks("发件人为空");
						}
					} else {
						mailLogDB.setFlag(4);
						mailLogDB.setRemarks("服务器配置失败");
					}
				} else {
					mailLogDB.setFlag(1);
					mailLogDB.setRemarks("不满意工单未处理数量为0");
				}
				mailLogDB.setCreateTime(new Date());
				mailLogDB.setModifyTime(new Date());
				mailLogDB.setTemplateType(1);
				int mailLogId = mailLogService.saveMailLog(mailLogDB);
				if (mailLogId <= 0) {
					logger.error("保存邮件发送日志信息失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.debug("=========结束执行不满意工单邮催任务");
	}

	/**
	 * 保留两位小数点
	 * @param number
	 * @return
	 */
	private static BigDecimal fixed(float number) {
		BigDecimal bigDecimal1 = new BigDecimal(Float.toString(number));
		BigDecimal result = bigDecimal1.setScale(2, BigDecimal.ROUND_HALF_UP);
		return result;
	}
	/**
	 * 将时间转换成yyyy/MM/dd HH:mm格式
	 * @param ts
	 * @return
	 */
	private static String getTimestampToString(Date ts){
		SimpleDateFormat dateformatAll= new SimpleDateFormat("yyyy/MM/dd HH:mm");//定义返回的日期格式
		return dateformatAll.format(new Timestamp(ts.getTime()));//格式化传过来的时间就可以去掉毫秒数
	}
}
